<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="60%">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { defineProps, ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/src/components/Modal';
  import { BasicForm, useForm } from '/src/components/Form';
  import { formSchemaTJ } from '../myApply.data';
  import { getFirstNode,applyBusiness } from '../myApply.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const props = defineProps({ dictId: String });
  const isUpdate = ref(true);
  const tempObj=ref();
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchemaTJ,
    showActionButtonGroup: false,
    mergeDynamicData: props,
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    console.log("tempObj.value",data.record)
    tempObj.value=data.record;

    let param={procDefId:data.record.procDefId,tableId:data.record.tableId,tableName:data.record.tableName}
    //请求回显数据
  await getFirstNode(param).then((res)=>{
      let temp=[];
      if (res.users && res.users.length > 0) {
        res.users.forEach(e => {
          temp.push({label: e.realname, value: e.username});
        });
      }
      console.log("temp",temp);
        //添加下拉值
      formSchemaTJ[0].componentProps.options=temp;
      console.log("formSchemaTJ",formSchemaTJ);
    })
    //重置表单
    await resetFields();
    //赋值
    setModalProps({ confirmLoading: false,schemas:formSchemaTJ});
    // isUpdate.value = !!data?.isUpdate;
    // if (unref(isUpdate)) {
    //   //表单赋值
    //   await setFieldsValue({
    //     ...data.record,
    //   });
    // }
  });

  //设置标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //表单提交事件
  async function handleSubmit(v) {
    try {
      setModalProps({ confirmLoading: true });
      const values = await validate();
      let formData = Object.assign(tempObj.value, values)
      console.log("formData",formData)
//       {
//     "priority": 0,
//     "assignees": "1401",
//     "sendMessage": true,
//     "id": "40283c128c90d81b018c90d81b4b0000",
//     "procDefId": "请假审批:1:5245",
//     "title": "请假审批",
//     "firstGateway": false
// }
      //提交表单
      await applyBusiness(formData);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
